﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace Extension {
  public static class ByteExt {
    /// <summary>
    /// 转为十六进制
    /// </summary>
    /// <param name="b"></param>
    /// <returns></returns>
    public static string ToHex(this byte b) {
      return b.ToString("X");
    }

    /// <summary>
    /// 转为十六进制
    /// </summary>
    /// <param name="bytes"></param>
    /// <param name="seperator">分隔符</param>
    /// <returns></returns>
    public static string ToHex(this IEnumerable<byte> bytes, string seperator = " ") {
      StringBuilder str = new StringBuilder();
      foreach (byte b in bytes) {
        str.Append(b.ToString("X"));
        str.Append(seperator);
      }

      return str.ToString();
    }
    /// <summary>
    /// 转为 Base64 字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string ToBase64String(this byte[] bytes) {
      return Convert.ToBase64String(bytes);
    }
    /// <summary>
    /// 转换为指定编码的字符串
    /// </summary>
    /// <param name="bytes">字节数组</param>
    /// <param name="encoding">编码类型</param>
    /// <returns></returns>
    public static string Decode(this byte[] bytes, Encoding encoding) {
      return encoding.GetString(bytes);
    }

    /// <summary>
    /// Hash
    /// </summary>
    /// <param name="bytes">字节数组</param>
    /// <param name="hashName">Hash 算法名称</param>
    /// <returns></returns>
    public static byte[] Hash(this byte[] bytes, string hashName = null) {
      HashAlgorithm algorithm;
      algorithm = hashName.IsNullOrEmptyOrWhiteSpace() ? HashAlgorithm.Create() : HashAlgorithm.Create(hashName);

      return algorithm.ComputeHash(bytes);
    }
  }
}
